package cn.j0n4than.api.interceptor;

import cn.j0n4than.api.entity.Auth;
import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 用户鉴权拦截器
 *
 * @author jonathan
 */
@Slf4j
public class AuthUserInterceptor extends BaseInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Auth auth;
        String token = request.getHeader("authorization");
        if (token != null) {
            try {
                String json = util.decrypt(token);
                auth = mapper.readValue(json, Auth.class);

                //判断请求IP是否是token中的ip
                if (!request.getRemoteAddr().equals(auth.ip)) {
                    log.info("请求IP和Token中的IP不一致");
                    return unauthorized(response);
                }

                //检查授权的权限
                if (!auth.type.equals(Auth.TYPE_USER)) {
                    log.info("授权类型不匹配");
                    return unauthorized(response);
                }

                //检查token是否过期
                if ((new Date()).getTime() > auth.expire.getTime()) {
                    log.info("Token过期");
                    return unauthorized(response);
                }
            } catch (RuntimeException e) {
                log.error("解密Token失败");
                log.error(e.getMessage());
                return unauthorized(response);
            } catch (JsonMappingException e) {
                log.error("解密Token映射到Auth实体失败");
                log.error(e.getMessage());
                return unauthorized(response);
            }

            request.setAttribute("auth", auth);
            return true;

        }

        return unauthorized(response);
    }
}
